<?php
namespace app\Manage\controller;

use app\common\controller\Manage;
use app\common\model\Operation as OperationModel;
use app\common\model\OperationIgnore as OperationIgnoreModel;
use think\facade\Log;
use think\Container;

use Request;

class Operation extends Manage
{
    public function index()
    {
        if(Request::isAjax()){
            $operationModel = new OperationModel();
            $data = input('param.');
            if(isset($data['parent_id']) && $data['parent_id'] != ""){
                //此处不需要做任何操作
            }else{
                $data['parent_id'] = $operationModel::MENU_MANAGE;
            }
            return $operationModel->tableData($data);
        }else{
            return $this->fetch('index');
        }
    }

    public function del()
    {
        if(!input('?param.id')){
            return error_code(10000);
        }
        $operationModel = new OperationModel();
        return $operationModel->toDel(input('param.id'));

    }

    //x新增和编辑
    public function add()
    {
        //$this->view->engine->layout(false);
        $operationModel = new OperationModel();
        if(Request::isPost()){
            return $operationModel->toAdd(input('param.'));
        }else{
            //如果是编辑，取数据
            if(input("?param.id")){
                $info = $operationModel->where(['id'=>input('param.id')])->find();
                if(!$info){
                    return error_code(10000);
                }
                $this->assign('info',$info);
            }

            //取全树
            $list = $operationModel->where('type','neq','a')->order('sort asc')->select()->toArray();
            $tree = $operationModel->createTree($list,$operationModel::MENU_START,'parent_id');
            $this->assign('tree',$tree);

            //取菜单树
            $menuList = $operationModel->where('perm_type','lt',3)->order('sort asc')->select()->toArray();
            $menuTree = $operationModel->createTree($menuList,$operationModel::MENU_START,'parent_menu_id');
            $this->assign('menuTree',$menuTree);

            return $this->fetch('add');
        }
    }


    //x新增和编辑
    public function edit()
    {
        //$this->view->engine->layout(false);
        $operationModel = new OperationModel();
        if(Request::isPost()){
            return $operationModel->toAdd(input('param.'));
        }else{
            //如果是编辑，取数据
            if(input("?param.id")){
                $info = $operationModel->where(['id'=>input('param.id')])->find();
                if(!$info){
                    return error_code(10000);
                }
                $this->assign('info',$info);
            }

            //取全树
            $list = $operationModel->where('type','neq','a')->order('sort asc')->select()->toArray();
            $tree = $operationModel->createTree($list,$operationModel::MENU_START,'parent_id');
            $this->assign('tree',$tree);

            //取菜单树
            $menuList = $operationModel->where('perm_type','lt',3)->order('sort asc')->select()->toArray();
            $menuTree = $operationModel->createTree($menuList,$operationModel::MENU_START,'parent_menu_id');
            $this->assign('menuTree',$menuTree);

            return $this->fetch('edit');
        }
    }

    /**
      * @cc 获取所有控制器名称
      *
      * @param $module
      *
      * @return array|null
      */
      protected  function  getController( $module ){
        if ( empty ( $module ))  return  null;
        $module_path  = Container::get('env')->get('app_path')  .  $module  .  '/controller/' ;   //控制器路径
        if (! is_dir ( $module_path ))  return  null;
        $module_path  .=  '/*.php' ;
        $ary_files  =  glob ( $module_path );

        foreach  ( $ary_files  as  $file ) {
            if  ( is_dir ( $file )) {
                continue ;
            } else  {
                $files [] =  basename ( $file, ".php" );
            }
        }
        return  $files ;
    }

    /**
     * @cc 获取所有方法名称
     *
     * @param  $module
     * @param  $controller
     *
     * @ return  array |null
     */
    protected  function  getAction( $module ,  $controller ){
        if ( empty ( $controller ))  return  null;
        $content  =  file_get_contents (Container::get('env')->get('app_path') .  $module . '/controller/' . $controller . '.php' );

        preg_match_all( "/.*?public.*?function(.*?)\(.*?\)/i" ,  $content ,  $matches );
        $functions  =  $matches [1];

        //排除部分方法
        $inherents_functions  =  array ('_initialize' , '__construct' , 'getActionName' , 'isAjax' , 'display' , 'show' , 'fetch' , 'buildHtml' , 'assign' , '__set' , 'get' , '__get' , '__isset' , '__call' , 'error' , 'success' , 'ajaxReturn' , 'redirect' , '__destruct' , '_empty' );
        foreach  ( $functions  as  $func ){
            $func  = trim( $func );
            if (!in_array( $func ,  $inherents_functions )){
              if  ( strlen ( $func )>0)    $customer_functions [] =  $func ;
            }
        }
        return  $customer_functions ;
    }
 
    /**
     * @cc 获取函数的注释
     *
     * @param $module Home
     * @param $controller Auth
     * @param $action index
     *
     * @return string 注释
     *
     */
    protected  function  get_cc_desc( $module , $controller , $action ){
        $desc = '\app\\' . $module . '\controller\\' . $controller;

        $func   =  new  \ReflectionMethod( new  $desc (), $action );
        $tmp    =  $func ->getDocComment();

        if($tmp){
            $flag   = preg_match_all( '/@cc(.*?)\n/' , $tmp , $tmp );
            if(array_key_exists(1, (array)$tmp) && array_key_exists(0, (array)$tmp[1])){           
                $tmp    = trim( $tmp [1][0]);
            }
        }
       
        $tmp    =  $tmp != ''  ?  $tmp : '无' ;
        return  $tmp ;
    }

    /**
     * @cc 生成权限
     *
     * @param  $module
     * @param  $controller
     *
     * @ return  array |null
     */
    public function auth()
    { 
        $operationModel = new OperationModel();
        $operationIgnoreModel = new OperationIgnoreModel();
        $IgnoreList = $operationIgnoreModel->select();

        $IgnoreArray = [];
        foreach($IgnoreList as $val) {
            $IgnoreArray[] = $val['control'].'-'.$val['func'];
        }
  
        if(Request::isAjax()){ 
            $modules  =  array ( 'manage' );   //模块名称
            
            $controlerList = $operationModel->field("id, code")->where(['type' => 'c'])->select();
            $actionList = $operationModel->field("parent_id, code")->where(['type' => 'a'])->select();
            $controlerIgnoreArray = [
                'Area', 
                'Balance', 
                'BillAftersales', 
                'BillDelivery', 
                'BillLading', 
                'BillPayments', 
                'BillRefund', 
                'BillReship', 
                'Categories', 
                'Common', 
                'Coupon', 
                'Device', 
                'DeviceCat', 
                'DeviceLogRepair', 
                'DeviceType', 
                'FeeTemplate', 
                'Files', 
                'Form', 
                'Goods', 
                'GoodsParams', 
                'GoodsType', 
                'GoodsTypeSpec', 
                'Ietask', 
                'Images', 
                'Index', 
                'Label', 
                'Logistics', 
                'Order', 
                'Brand', 
                'DeviceLog', 
                'Pages', 
                'Payments', 
                'Promotion', 
                'Recharge', 
                'Report', 
                'Ship', 
                'Store', 
                'WxBill', 
                ];
            
            $controlerArray = [];
            foreach  ( $controlerList  as  $val ) {
                $controlerArray[$val['code']] = $val['id'];
            }
 
            $actionArray = [];
            foreach  ( $actionList  as  $val ) {
                $actionArray[] = $val['parent_id'].'_'.$val['code'];
            }
 
            $data = [];
            foreach  ( $modules  as  $module ) {
                $all_controller  =  $this ->getController( $module ); 
                foreach  ( $all_controller  as  $controller ) {
                    $controller_name  =  $controller ;
                    $all_action  =  $this ->getAction( $module ,  $controller_name );
                    foreach  ( $all_action  as  $action ) {
                        $desc = '';
                        $error = false;

                        if(!in_array($controller, $controlerIgnoreArray) && 
                           !in_array($controller.'-'.strtolower($action), $IgnoreArray)) {
                            if(!array_key_exists($controller, $controlerArray) ){
                                $desc = "控制器不存在";
                                $error = true;
                            } else {
                                $key = $controlerArray[$controller].'_'.strtolower($action); 

                                if( !in_array($key, $actionArray) && !$operationModel->checkNeedPerm('2', $controller, strtolower($action)) ){
                                    $desc = "Action不存在";
                                    $error = true;
                                }
                            }
    
                            if( $error ){
                                $data [] =  array (
                                    'controlerName' => $controller,
                                    'controler' => $controller,
                                    'funcName' => $this ->get_cc_desc( $module , $controller , $action ),
                                    'func' => strtolower($action),
                                    'desc' => $desc
                                );
                            }
                        }
                    }
                }
            } 
 
            $re['code'] = 0;
            $re['msg'] = '';
            $re['count'] = count($data);
            $re['data'] = $data;

            return $re; 
        }else{
            return $this->fetch('auth');
        }
    }
}
